<template>
  <div class="app-main-container">
    <div class="dinner_wrap">
      <div class="app-main-title">
        {{ $t('message.dc') }}
        <div class="goback" @click="goBack">
          <i class="el-icon-refresh-left" /> {{ $t('message.fhsyy') }}
        </div>
      </div>

      <div style="margin-bottom: 20px; width: 35%">
        <el-input
          v-model="goodsName"
          :placeholder="$t('message.qsr') + $t('message.spmc')"
          class="input-with-select"
          clearable
          @change="nameChage"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleCurrentChange(1)"
          />
        </el-input>
      </div>
      <div>
        <el-tabs v-model="selId" @tab-click="handleClick">
          <el-tab-pane
            v-for="item in classList"
            :key="item.id"
            :label="item.name"
            :name="item.id"
          />
        </el-tabs>
        <!-- <div
          v-for="item in classList"
          :key="item.id"
          class="class-item-nor"
          :class="item.id==selId ? 'class-item-sel' : ''"
          @click="selectClass(item)"
        >{{ item.name }}</div> -->
      </div>

      <div class="goods-contant">
        <div v-for="item in goodsLsit" :key="item.list" class="goods-item">
          <img :src="item.picture" alt="">
          <div class="goods-message">
            <div class="goods-name">{{ item.name }}</div>
            <div class="goods-stock">{{ $t('message.kucun') }}：{{ item.stock || $t('message.bx') }}</div>
            <div class="goods-price">{{ item.price }}</div>
          </div>
          <!-- <div class="add-btn" @click="addShopCart(item)">{{ item.goodsSkuIds ? '规格' : '添加' }}</div> -->
          <el-button
            class="add-btn"
            type="primary"
            @click="addShopCart(item)"
          >{{ $t('message.tijia') }}</el-button>
        </div>
      </div>

      <div class="flex-cc doumee-pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalCount"
          :current-page.sync="pagination.page"
          :page-size="6"
          hide-on-single-page
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <div class="shop-cart">
      <div class="shop-cart-header">
        <div class="order-title">{{ $t('message.dgsp') }}</div>
        <div class="header-right">
          <div class="total-price">{{ totalPrice }}</div>
          <el-button type="primary" @click="settleAccount">{{ $t('message.jiezhan') }}</el-button>
        </div>
      </div>
      <div v-for="item in cartList" :key="item.orderId">
        <div class="sub-title">
          {{ item.status == 0 ? this.$t('message.wxd') : $t('message.yxd') + `：${item.orderTime}` }}
        </div>
        <el-table
          ref="table"
          :data="item.goodsList"
          element-loading-text="Loading"
          border
          fit
          :header-row-class-name="'table-header'"
          class="doumee-element-table"
        >
          <el-table-column align="center" type="index" width="50" />
          <el-table-column
            align="center"
            :label="$t('message.spmc')"
            min-width="140"
            prop="name"
          />
          <el-table-column
            align="center"
            :label="$t('message.guige')"
            min-width="180"
            prop="goodsSkuInfo"
          />
          <el-table-column
            align="center"
            :label="$t('message.price')"
            min-width="100"
            prop="price"
          />
          <el-table-column
            align="center"
            :label="$t('message.spkc')"
            min-width="100"
            prop="stock"
          />
          <el-table-column
            align="center"
            :label="$t('message.num')"
            min-width="100"
            prop="num"
          />
          <el-table-column align="center" :label="$t('message.spzj')" min-width="120">
            <template scope="{ row }">
              {{ +row.price * row.num }}
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('message.caozuo')" min-width="200">
            <template scope="{ row }">
              <el-button
                type="text"
                class="secondColor"
                @click="delCart(row.cartId)"
              >{{ item.status == 0 ? $t('message.del'): $t('message.tucan') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="order-bottom">
          <div class="price">{{ item.amount }}</div>
          <div>
            <el-button
              v-if="item.status == 0"
              v-preventReClick
              type="danger"
              @click="putOrder"
            >{{ $t('message.xiadan') }}</el-button>
            <el-button
              v-if="item.status == 1"
              v-preventReClick
              type="danger"
              @click="print(item.orderId)"
            >{{ $t('message.dayin') }}</el-button>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      :title="$t('message.ggxq')"
      :visible.sync="selectSku"
      width="30%"
      :close-on-click-modal="modalDialog"
      :close-on-press-escape="modalDialog"
      center
      @close="skuClose"
    >
      <div class="sku-goods-name">{{ tempGoods.name }}</div>
      <div
        v-for="(item, i) in tempGoods.skuList"
        :key="item.id"
        class="sku-style"
      >
        <div class="sku-title-style">{{ item.name }}</div>
        <div class="sku-item-style">
          <div
            v-for="(val, index) in item.valList"
            :key="val.id"
            class="sku-val"
            :class="index == selectSkuList[i] ? 'sku-val-sel' : ''"
            @click="selectSkuAction(i, index)"
          >
            {{ val.val }}
          </div>
        </div>
      </div>
      <div>
        {{ $t('message.num') }}
        <el-input-number
          v-model="tempNum"
          :min="1"
          :max="tempGoods.stock || Infinity"
          :label="$t('message.num')"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-preventReClick
          type="primary"
          @click="addshopCartAction(tempGoods.id)"
        >{{ $t('message.qd') }}</el-button>
        <el-button
          type="primary"
          plain
          @click="selectSku = false"
        >{{ $t('message.qx') }}</el-button>
      </div>
    </el-dialog>
    <orderDialog ref="child" @orderSuccess="getOrderList" />
  </div>
</template>

<script>
import {
  goodsClassifyListVenue,
  goodsListVenue,
  addGoodsCarts,
  goodsCartList,
  goodsEditQuery,
  delGoodsCarts,
  goodsCartXD,
  printOrder
} from '@/api'
import store from '@/store'
import orderDialog from '@/components/order'

export default {
  components: { orderDialog },
  data() {
    return {
      goodsRestaurantId: '',
      modalDialog: store.getters.dialog,
      goodsName: '',
      classList: [],
      selId: '0',

      goodsLsit: [],
      pagination: {
        page: 1,
        rows: 6
      },
      totalCount: 0,
      tempGoods: {},
      tempNum: 1,
      selectSkuList: [],
      selectSku: false,

      cartList: [],
      cartNum: 0,
      totalPrice: 0
    }
  },
  created() {
    this.goodsRestaurantId = this.$route.query.goodsRestaurantId || ''
    goodsClassifyListVenue({
      param: {
        saleType: 1,
        goodsRestaurantId: this.goodsRestaurantId,
        venueId: sessionStorage.getItem('venueId')
      }
    }).then((res) => {
      if (res.errorCode === '000000') {
        this.classList = [
          { id: '0', name: this.$t('message.qb'), sort: 0 },
          ...res.recordList
        ]
      }
    })

    this.getOrderList()
    this.handleCurrentChange(1)
  },
  activated() {
    this.$refs.table.doLayout()
  },
  methods: {
    nameChage(v) {},
    /**
     * @desc 获取购物车列表
     */
    getOrderList() {
      goodsCartList({
        param: {
          goodsTableId: this.$route.query.id,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        this.cartList = res.record.cartList
        this.cartNum = res.record.totalNum
        this.totalPrice = res.record.totalPrice
      })
    },
    /**
     * @description 选择分类
     * @param {*} item
     */
    selectClass(item) {
      this.selId = item.id
      this.handleCurrentChange(1)
    },
    handleClick(tab, event) {
      // this.selId = tab.name
      // for (const type of this.typeList) {
      //   console.log(this.activeType, type.id)
      //   if (this.activeType === type.id) {
      //     this.selectType = type
      //   }
      // }
      // this.getList()
      this.handleCurrentChange(1)
    },
    /**
     * @description 加入购物车
     * @param {@} item
     */
    addShopCart(item) {
      console.log(item)
      if (item.stock === '0') {
        return this.$message.info(this.$t('message.zsspkc'))
      }
      if (item.goodsSkuIds) {
        goodsEditQuery({
          param: { id: item.id }
        }).then((res) => {
          if (res.errorCode !== '000000') return
          this.tempGoods = res.record
          // this.tempGoods.stock = +this.tempGoods.stock
          this.selectSku = true
          this.selectSkuList = []
          res.record.skuList.forEach((item, index) => {
            this.$set(this.selectSkuList, index, 0)
          })
        })
      } else {
        this.addshopCartAction(item.id)
      }
    },
    selectSkuAction(index, val) {
      this.$set(this.selectSkuList, index, val)
    },

    handleCurrentChange(page) {
      const pagination = this.pagination
      if (page) {
        this.pagination.page = page
        pagination.page = page
      }
      const classId = this.selId === '0' ? '' : this.selId
      goodsListVenue({
        pagination,
        param: {
          name: this.goodsName,
          classifyId: classId,
          status: '1',
          type: '1',
          venueId: sessionStorage.getItem('venueId'),
          saleType: 1,
          goodsRestaurantId: this.goodsRestaurantId
        }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        this.goodsLsit = res.recordList
        this.totalCount = res.totalCount
      })
    },
    skuClose() {
      this.tempNum = 1
      this.selectSkuList = []
    },
    goBack() {
      this.$router.replace(
        `/application/ordering?activeTwo=${this.goodsRestaurantId}`
      )
    },
    addshopCartAction(id) {
      let goodsSkuInfo = ''
      const infoArr = []
      if (this.selectSkuList) {
        // this.selectSkuList.forEach(e => {
        //   infoArr.push(this.tempGoods.skuList[e].valList[this.selectSkuList[e]].val)
        // })
        for (const key in this.selectSkuList) {
          infoArr.push(
            this.tempGoods.skuList[key].valList[this.selectSkuList[key]].val
          )
        }
        goodsSkuInfo = infoArr.join('/')
        console.log(infoArr)
      }
      addGoodsCarts({
        param: {
          goodsTableId: this.$route.query.id,
          venueId: sessionStorage.getItem('venueId'),
          goodsList: [
            {
              goodsId: id,
              num: this.tempNum,
              goodsSkuInfo
            }
          ]
        }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        this.selectSku = false
        this.tempNum = 1
        this.getOrderList()
      })
    },
    /**
     * 删除购物车
     * @param {} id
     */
    delCart(id) {
      delGoodsCarts({
        param: { id }
      }).then((res) => {
        if (res.errorCode === '000000') {
          this.$message.success(this.$t('message.delcg'))
          this.getOrderList()
        } else {
          this.$message.success(res.errorMsg)
        }
      })
    },
    /**
     * @desc 下单
     */
    putOrder() {
      this.$prompt(this.$t('message.qsr') + this.$t('message.bz'), this.$t('message.ts'), {
        confirmButtonText: this.$t('message.qd'),
        cancelButtonText: this.$t('message.qx')
      })
        .then(({ value }) => {
          goodsCartXD({
            param: {
              goodsTableId: this.$route.query.id,
              remark: value
            }
          }).then((res) => {
            if (res.errorCode === '000000') {
              this.$message.success(this.$t('message.xdcg'))
              // this.print(res.record.orderId)
              this.getOrderList()
            } else {
              this.$message.success(res.errorMsg)
            }
          })
        })
        .catch(() => {})
    },
    settleAccount() {
      if (!this.cartList.length) {
        this.$message.warning(this.$t('message.qxtjspdgwc'))
        return
      }
      const goodsList = []
      this.cartList.forEach((item) => {
        item.goodsList.forEach((goods) => {
          goodsList.push({
            id: goods.goodsId,
            goodsNum: goods.num,
            skuInfo: goods.goodsSkuInfo
          })
        })
      })
      this.$refs.child.continuePay(goodsList, 'dinner', this.$route.query.id)
    },
    print(workId) {
      printOrder({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          templateCode: 'GOODSTPML3',
          workId
        }
      }).then((res) => {
        if (res.errorCode === '000000') {
          this.$message.success(this.$t('message.dycg'))
        } else {
          this.$message.error(res.errorMsg)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dinner_wrap {
  background-color: #fff;
  .class-list {
    overflow: scroll;
    height: 40px;
    font-size: 14px;
    text-align: center;
    display: flex;
    .class-item-nor {
      border-radius: 4px;
      background-color: #fff;
      color: #111;
      height: 24px;
      line-height: 24px;
      width: 80px;
      margin-right: 15px;
      cursor: pointer;
    }
    .class-item-sel {
      background-color: rgb(148, 209, 244);
      color: #fff;
    }
  }
  .goods-contant {
    display: flex;

    flex-wrap: wrap;
    margin-top: 10px;
    .goods-item {
      width: calc(33% - 18px);
      background-color: #f7f7f7;
      margin: 8px;
      height: 110px;
      display: flex;
      box-sizing: border-box;
      padding: 10px;
      position: relative;

      img {
        height: 100%;
        aspect-ratio: 1;
        object-fit: contain;
      }
      .goods-message {
        margin-left: 10px;
        font-size: 14px;
        .goods-name {
          margin-top: 10px;
          margin-bottom: 10px;
        }
        .goods-stock {
          font-size: 12px;
          color: #666;
        }
        .goods-price {
          font-size: 18px;
          color: rgb(199, 42, 41);
          margin-top: 15px;
          font-weight: 500;
          &:before {
            // content: "￥";
          }
        }
      }
      .add-btn {
        position: absolute;
        right: 10px;
        bottom: 10px;
        width: 80px;
        text-align: center;
        cursor: pointer;
      }
    }
  }
  .sku-goods-name {
    font-size: 16px;
    font-weight: 500;
    color: #111;
    margin-bottom: 20px;
  }
  .sku-style {
    margin-bottom: 20px;

    .sku-title-style {
      color: #222;
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 10px;
    }
    .sku-item-style {
      display: flex;
      flex-wrap: wrap;
      .sku-val {
        font-size: 13px;
        padding: 5px 10px;
        color: #333;
        border: #333 solid 0.5px;
        background-color: #fff;
        margin-right: 5px;
        border-radius: 4px;
        cursor: pointer;
        margin-bottom: 5px;
      }
      .sku-val-sel {
        color: rgb(230, 199, 25);
        border: rgb(230, 199, 25) solid 0.5px;
        background-color: rgba(230, 199, 25, 0.1);
      }
    }
  }
  .shop-cart {
    border-top: #f7f7f7 solid 10px;
    padding: 20px;
    background-color: #fff;
    .shop-cart-header {
      display: flex;
      justify-content: space-between;
      .header-right {
        display: flex;
        .total-price {
          line-height: 40px;
          color: rgb(199, 42, 41);
          font-size: 18px;
          font-weight: 500;
          margin-right: 20px;
          &:before {
            // content: "订单合计：";
            color: #111;
            font-size: 14px;
            font-weight: normal;
          }
        }
      }
    }
  }

  .order-title {
    font-size: 18px;
    font-weight: 500;
    color: #111;
    background-color: #fff;
    height: 40px;
    line-height: 40px;
  }
  .sub-title {
    font-size: 16px;
    color: #333;
    height: 30px;
    line-height: 30px;
  }
  .order-bottom {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    height: 60px;

    background-color: #fff;
    border-left: rgb(223, 225, 230) solid 1px;
    border-right: rgb(223, 225, 230) solid 1px;
    border-bottom: rgb(223, 225, 230) solid 1px;
    .price {
      line-height: 40px;
      color: rgb(199, 42, 41);
      font-size: 18px;
      font-weight: 500;
      &:before {
       // content: "订单合计：";
        color: #111;
        font-size: 14px;
        font-weight: normal;
      }
    }
  }
}
</style>
